import { tool } from '@openai/agents';
import { z } from 'zod';
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

export const generateAiImage = tool({
  name: 'generate_ai_image',
  description: 'Generate AI images using DALL-E for vocabulary learning contexts',
  parameters: z.object({
    context: z.string().describe('The vocabulary learning context to create an image for'),
    sessionId: z.string().nullable().describe('Session ID for tracking user images')
  }),
  async execute({ context, sessionId }) {
    try {
      // Create vocabulary-rich prompt for DALL-E
      const enhancedPrompt = await createVocabularyRichPrompt(context);
      console.log('📝 Enhanced prompt for DALL-E:', enhancedPrompt);
      
      const response = await openai.images.generate({
        model: 'dall-e-3',
        prompt: enhancedPrompt,
        size: '1024x1024',
        quality: 'standard',
        n: 1,
        response_format: 'url'
      });

      if (!response.data || response.data.length === 0 || !response.data[0].url) {
        throw new Error('No image was generated or URL is missing');
      }

      const imageUrl = response.data[0].url;
      const imageId = `dalle3_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      return {
        id: imageId,
        url: imageUrl,
        alt_description: `A detailed scene showing ${context}`,
        description: `AI-generated image depicting ${context} with rich vocabulary opportunities`,
        prompt: enhancedPrompt,
        source: 'dall-e' as const
      };
    } catch (error) {
      console.error('Error generating image with DALL-E:', error);
      throw new Error(`Failed to generate AI image: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }
});

async function createVocabularyRichPrompt(context: string): Promise<string> {
  try {
    const prompt = `Create a simple scene description for DALL-E image generation showing: "${context}"

Keep it directly related to ${context}. Show typical objects, tools, and activities found in/for ${context}.

Generate ONLY the scene description, no explanations.`;

    const response = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [{ role: "user", content: prompt }],
      temperature: 0.3,
      max_tokens: 150
    });

    const generatedScene = response.choices[0].message.content?.trim();
    
    if (!generatedScene) {
      throw new Error('No scene generated by LLM');
    }

    return `${generatedScene}, realistic photography style, detailed and clear, rich in visual elements for vocabulary learning`;
    
  } catch (error) {
    console.error('Error generating prompt with LLM:', error);
    return `${context}, realistic photography style, detailed scene with multiple objects and elements, rich in visual details for vocabulary learning`;
  }
}